﻿using cap_demo.Domain.Abstractions;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cap_demo.Infrastructure.Extensions
{
    public static class MediatorExtension
    {
        /// <summary>
        /// 分发领域事件
        /// </summary>
        /// <param name="mediator"></param>
        /// <param name="context">Context上下文</param>
        /// <returns></returns>
        public static async Task DispatchDomainEventAsync(this IMediator mediator, DbContext context)
        {
            // 筛查出当前DbContext中存在领域事件的实体集合
            var domainEntities = context.ChangeTracker.Entries<Entity>().Where(x => x.Entity.DomainEvents?.Any() == true);

            var domainEvents = domainEntities.SelectMany(x => x.Entity.DomainEvents).ToList();

            // 清空当前实体领域事件
            domainEntities.ToList().ForEach(entity => entity.Entity.ClearDomainEvent());

            foreach (var domainEvent in domainEvents)
            {
                await mediator.Publish(domainEvent);
            }

        }

    }
}
